package com.easyadmin.pro.common.interceptor;

import com.easyadmin.pro.common.constants.BaseConstants;
import com.easyadmin.pro.common.entity.BaseEntity;
import com.easyadmin.pro.tool.WebUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Objects;
/**
 * packageName com.easyadmin.pro.common.interceptor
 *
 * @author 骑着蚂蚁去上天
 * @version JDK 17
 * @className MybatisMetaObjectInterceptor
 * @date 2024/4/7
 * @description mybatis 数据前置拦截器
 */
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisMetaObjectInterceptor implements Interceptor {

    /**
     * 拦截方法
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        // 获取 SQL 命令
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        // 只处理新增跟修改
        if (Objects.equals(SqlCommandType.INSERT, sqlCommandType)
                || Objects.equals(SqlCommandType.UPDATE, sqlCommandType)) {
            // 获取参数
            Object parameter = invocation.getArgs()[1];
            MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
            Object obj = map.get(BaseConstants.PARAM);
            // 业务逻辑处理
            dealParameter(obj, sqlCommandType);
        }
        return invocation.proceed();
    }

    /**
     * 处理参数
     * @param parameter
     * @param sqlCommandType
     */
    private void dealParameter(Object parameter, SqlCommandType sqlCommandType) throws IllegalAccessException {
        Class<?> aClass = parameter.getClass();
        Field[] declaredFields;
        // 父类不为BaseEntity说明不需要处理
        if (!BaseEntity.class.isAssignableFrom(aClass)) {
            return;
        }
        // 获取父类私有成员变量
        declaredFields = aClass.getSuperclass().getDeclaredFields();
        for (Field field : declaredFields) {
            // insert 语句插入 创建人、创建时间
            if (Objects.equals(SqlCommandType.INSERT, sqlCommandType)) {
                if (Objects.equals(BaseConstants.CREATE_USER_ID, field.getName())) {
                    field.setAccessible(true);
                    try {
                        field.set(parameter, WebUtils.getUserId());
                    } catch (Exception e) {
                        field.set(parameter, 1L);
                    }
                }
                if (Objects.equals(BaseConstants.CREATE_TIME, field.getName())) {
                    field.setAccessible(true);
                    field.set(parameter, LocalDateTime.now());
                }
            }

            // update 语句插入 更新人、更新时间
            if (Objects.equals(SqlCommandType.UPDATE, sqlCommandType)) {
                if (Objects.equals(BaseConstants.UPDATE_USER_ID, field.getName())) {
                    field.setAccessible(true);
                    try {
                        field.set(parameter, WebUtils.getUserId());
                    } catch (Exception e) {
                        field.set(parameter, 1L);
                    }
                }
                if (Objects.equals(BaseConstants.UPDATE_TIME, field.getName())) {
                    field.setAccessible(true);
                    field.set(parameter, LocalDateTime.now());
                }
            }
        }
    }
}